/*
 * @Description: axios
 */
import axios from 'axios'
import { ElMessage } from 'element-plus';

axios.defaults.timeout = 10000;

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token');
  config.headers.Authorization = `Bearer ${token}`
  return config;
}, function (error) {
  return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  const authorization = response.headers.authorization;
  authorization && localStorage.setItem('token', authorization)
  return response.data;
}, function (error) {
  if (error.response.status) {
    const { status } = error.response;
    switch (status) {
      case 401:
        localStorage.removeItem('token')
        window.location.href = '#/login'
        break;
      case 403:
        ElMessage.warning('登录过期，请重新登录');
        setTimeout(() => {
          window.location.href = '#/login'
        }, 1000);
        break;
      default:
        break;
    }
  }
  return Promise.reject(error);
});